﻿namespace Vdc.Grid
{
    using System;
    using System.Collections;
    using System.Web.UI;

    public class GridPersistentCollection : CollectionBase, IStateManager
    {
        private bool _isTrackingViewState;
        private StateBag _viewState;

        protected virtual void LoadViewState(object savedState)
        {
            if (savedState != null)
            {
                ((IStateManager) this.ViewState).LoadViewState(savedState);
            }
        }

        protected virtual object SaveViewState()
        {
            if (this._viewState != null)
            {
                return ((IStateManager) this.ViewState).SaveViewState();
            }
            return null;
        }

        void IStateManager.LoadViewState(object savedState)
        {
            this.LoadViewState(savedState);
        }

        object IStateManager.SaveViewState()
        {
            return this.SaveViewState();
        }

        void IStateManager.TrackViewState()
        {
            this.TrackViewState();
        }

        protected virtual void TrackViewState()
        {
            this._isTrackingViewState = true;
            if (this._viewState != null)
            {
                ((IStateManager) this.ViewState).TrackViewState();
            }
        }

        protected virtual bool IsTrackingViewState
        {
            get
            {
                return this._isTrackingViewState;
            }
        }

        bool IStateManager.IsTrackingViewState
        {
            get
            {
                return this.IsTrackingViewState;
            }
        }

        protected virtual StateBag ViewState
        {
            get
            {
                if (this._viewState == null)
                {
                    this._viewState = new StateBag();
                    if (this.IsTrackingViewState)
                    {
                        ((IStateManager) this._viewState).TrackViewState();
                    }
                }
                return this._viewState;
            }
        }
    }
}

